package com.lwq.project.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class MyInterceptor extends HandlerInterceptorAdapter {
	
	Logger logger = Logger.getLogger(MyInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		logger.error("======拦截器关闭====afterCompletion=========");
	}
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		logger.error("=======执行处理完毕=====postHandle============");
		long starttime = (Long) arg0.getAttribute("starttime");
		arg0.removeAttribute("starttimes");
		long endtime = System.currentTimeMillis();
		logger.error("请求地址："+arg0.getRequestURL()+"处理时间：{"+(endtime-starttime)+"}ms");
		
	}
	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		logger.error("=======拦截器启动======preHandle============");
		String url = arg0.getRequestURL().toString();
		logger.error("请求的uri："+url);
		arg0.setAttribute("starttime", System.currentTimeMillis());
		if(!StringUtils.isBlank((CharSequence) arg0.getSession().getAttribute("uPrimary"))){
			logger.error("uPrimary:" + arg0.getSession().getAttribute("uPrimary"));
			logger.error("rPrimary:" + arg0.getSession().getAttribute("rPrimary"));
			logger.error("uName:" + arg0.getSession().getAttribute("uName"));
			return true;
		}
		logger.error("=======拦截成功跳转到登录页面");
		arg0.getRequestDispatcher("/login.action").forward(arg0, arg1);
		return false;
	}

}
